package grobit.tracker

import grobit.torrent.Sha1Data

class TrackerRequest {
    String tracker
    Sha1Data info_hash
    BigInteger port
    BigInteger uploaded = 0
    BigInteger downloaded = 0
    BigInteger left
    boolean compact = true
    String event = 'started'

    String getRequest() {
        List params = []
        params.add(param('info_hash', info_hash.asString()))
        params.add(param('peer_id', new String(PeerId.get(), 'ISO-8859-1')))
        params.add(param('port', port))
        params.add(param('uploaded', uploaded))
        params.add(param('downloaded', downloaded))
        params.add(param('left', left))
        params.add(param('compact', compact ? 1 : 0))
        // no_peer_id - not needed with compact on
        params.add(param('event', event))
        // optional: ip, numwant, key, trackerid

        return (tracker + '?' + params.join('&'))
    }

    static param(String name, Number val) {
        return param(name, val.toString())
    }

    static param(String name, String val) {
        return name + '=' + asUrlString(val)
    }

    /**
     * An over-enthusiastic encoding routine, all non-alphanumerics are encoded.
     * @return
     */
    static String asUrlString(String s) {
        StringBuilder builder = new StringBuilder()
        s.getBytes('ISO-8859-1').each { val ->
            if(val as char ==~ /[A-Za-z0-9]/) {
                builder.append(val as char)
            } else {
                builder.append(String.format("%%%02X", val))
            }
        }
        return builder.toString()
    }

    @Override
    public String toString() {
        return "TrackerRequest{" +
                "tracker='" + tracker + '\'' +
                ", info_hash=" + info_hash +
                ", port=" + port +
                ", uploaded=" + uploaded +
                ", downloaded=" + downloaded +
                ", left=" + left +
                ", compact=" + compact +
                '}';
    }
}
